package com.gdsz.libbasic.extensions

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.Keep
import androidx.databinding.ViewDataBinding
import androidx.viewbinding.ViewBinding

import java.lang.reflect.ParameterizedType


@Keep
fun <VB : ViewBinding> Any.getViewBinding(inflater: LayoutInflater, position: Int = 0): VB {
    val vbClass =
        (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments.filterIsInstance<Class<*>>()
    val inflate = vbClass[position].getDeclaredMethod("inflate", LayoutInflater::class.java)
    return inflate.invoke(null, inflater) as VB
}

@Keep
fun <VB : ViewBinding> Any.getViewBinding(
    inflater: LayoutInflater,
    container: ViewGroup?,
    position: Int = 0
): VB {
    val vbClass =
        (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments.filterIsInstance<Class<VB>>()
    val inflate = vbClass[position].getDeclaredMethod(
        "inflate",
        LayoutInflater::class.java,
        ViewGroup::class.java,
        Boolean::class.java
    )
    return inflate.invoke(null, inflater, container, false) as VB
}
@Keep
fun <VB : ViewDataBinding> Any.loadLayout(vbClass: Class<VB>, parent: ViewGroup): VB {
    val inflate = vbClass.getDeclaredMethod(
        "inflate",
        LayoutInflater::class.java,
        ViewGroup::class.java,
        Boolean::class.java
    )
    return inflate.invoke(null, LayoutInflater.from(parent.context), parent, false) as VB
}

